package com.xu.wemall.test;

import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * HTML转PDF文件
 */
public class HtmlToPdfConverter {
    public static void main(String[] args) {
        try {
            String htmlContent = "<html><head></head><body><h1>Hello, World!</h1></body></html>";
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(htmlContent);

            // 解决中文不显示的问题
            ITextFontResolver fontResolver = renderer.getFontResolver();
            //fontResolver.addFont("D:\\JavaDevelop\\fonts\\微软雅黑.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            // 解决图片不显示的问题
            renderer.getSharedContext().setBaseURL("file:///path/to/html/files/");

            OutputStream os = Files.newOutputStream(Paths.get("D://output.pdf"));
            renderer.layout();
            renderer.createPDF(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}